<!--  -->
<template>
  <div class="process-container">
    <div class="table__wrapper">
      <transition :enter-active-class="this.animate.searchAnimate.enter" :leave-active-class="this.animate.searchAnimate.leave">
        <div class="search" v-show="showSearch">
          <el-form :model="queryParams" ref="queryFormRef" size="small" :inline="true" label-width="68px">
              <el-form-item label="套餐名称" prop="packageName">
                <el-input v-model="queryParams.packageName" placeholder="请输入套餐名称" clearable style="width: 240px" @keyup.enter="handleQuery" />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>
        </div>
      </transition>
      <div class="table-operates">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAdd" v-hasPermi="['system:tenantPackage:add']"> 新增 </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" size="mini" icon="el-icon-edit-outline" :disabled="single" @click="handleUpdate()" v-hasPermi="['system:tenantPackage:edit']">
              修改
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" size="mini" icon="el-icon-delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['system:tenantPackage:remove']">
              删除
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" size="mini" icon="el-icon-download" @click="handleExport" v-hasPermi="['system:tenantPackage:export']">导出 </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </div>
      <el-table v-loading="loading" :data="tenantPackageList" height="100%" @selection-change="handleSelectionChange" class="common-table">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="租户套餐id" align="center" prop="packageId" v-if="false" />
        <el-table-column label="套餐名称" prop="packageName" />
        <el-table-column label="流量类型">
          <template #default="scope">
            <dict-tag :options="dict.type.sys_limiter_type" :value="scope.row.limiterType" />
          </template>
        </el-table-column>
        <el-table-column label="速率">
          <template #default="scope">
            <span v-if="scope.row.limiterType === 'system'">不限流量</span>
            <span v-else-if="scope.row.limiterType === 'time'">速率: {{scope.row.rate}}次<br/>时间窗口: {{scope.row.rateInterval}}秒</span>
            <span v-else-if="scope.row.limiterType === 'token'">每秒产生的令牌数: {{scope.row.rate}}<br/>令牌桶容量: {{scope.row.bucketCapacity}}<br/>请求消耗的令牌数: {{scope.row.requestedTokens}}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" />
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="流量设置" placement="top">
              <el-button type="text" icon="el-icon-setting" @click="handleSettings(scope.row)" v-hasPermi="['system:tenantPackage:setting']"></el-button>
            </el-tooltip>
            <el-tooltip content="修改" placement="top">
              <el-button type="text" icon="el-icon-edit-outline" @click="handleUpdate(scope.row)" v-hasPermi="['system:tenantPackage:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:tenantPackage:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </div>

    <!-- 添加或修改租户套餐对话框 -->
    <el-dialog :title="dialog.title" :visible.sync="dialog.visible" width="500px" append-to-body>
      <el-form ref="tenantPackageFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="套餐名称" prop="packageName">
          <el-input v-model="form.packageName" placeholder="请输入套餐名称" />
        </el-form-item>
        <el-form-item label="关联菜单">
          <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menu')">展开/折叠</el-checkbox>
          <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menu')">全选/全不选 </el-checkbox>
          <el-checkbox v-model="form.menuCheckStrictly" @change="handleCheckedTreeConnect($event, 'menu')">父子联动 </el-checkbox>
          <el-tree
            class="tree-border"
            :data="menuOptions"
            show-checkbox
            ref="menuTreeRef"
            node-key="id"
            :check-strictly="!form.menuCheckStrictly"
            empty-text="加载中，请稍候"
            :props="{ label: 'label', children: 'children' }"
          ></el-tree>
        </el-form-item>
        <el-form-item label="客户端数" prop="maxClient">
          <el-input-number v-model="form.maxClient" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <LimiterSetting :visible.sync="showLimiterSetting" :dataSource="curPackage"/>
  </div>
</template>

<script>
import {
  listTenantPackage,
  getTenantPackage,
  delTenantPackage,
  addTenantPackage,
  updateTenantPackage,
  changePackageStatus
} from "@/api/system/tenantPackage";
import { treeselect as menuTreeselect, tenantPackageMenuTreeselect } from "@/api/system/menu";
import to from "await-to-js";
import LimiterSetting from '../tenantPackage/limiterSetting.vue';

const initFormData = {
  packageId: undefined,
  packageName: "",
  menuIds: "",
  remark: "",
  menuCheckStrictly: true,
  maxClient: 3
};

export default {
  name:"TenantPackage",
  dicts: ['sys_limiter_type'],
  //import引入的组件需要注入到对象中才能使用
  components: {LimiterSetting},
  data() {
    //这里存放数据
    return {
      showLimiterSetting: false,
      curPackage: null,
      tenantPackageList: [],
      buttonLoading: false,
      loading: true,
      showSearch: true,
      ids: [],
      single: true,
      multiple: true,
      total: 0,
      menuExpand: false,
      menuNodeAll: false,
      menuOptions: [],
      dialog: {
        visible: false,
        title: ""
      },
      form: { ...initFormData },
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        packageName: ""
      },
      rules: {
        packageId: [{ required: true, message: "租户套餐id不能为空", trigger: "blur" }],
        packageName: [{ required: true, message: "套餐名称不能为空", trigger: "blur" }]
      }
    }
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {
    
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {

  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.getList()
  },
  //方法集合
  methods: {
    /** 查询菜单树结构 */
    async getMenuTreeselect() {
      const { data } = await menuTreeselect();
      this.menuOptions = data;
    },

    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menuTreeRef.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menuTreeRef.getHalfCheckedKeys();
      if (halfCheckedKeys) {
        checkedKeys?.unshift.apply(checkedKeys, halfCheckedKeys);
      }
      return checkedKeys;
    },

    /** 根据租户套餐ID查询菜单树结构 */
    async getPackageMenuTreeselect(packageId) {
      let res = await tenantPackageMenuTreeselect(packageId);
      this.menuOptions = res.data.menus;
      return Promise.resolve(res);
    },

    /** 查询租户套餐列表 */
    async getList() {
      this.loading = true;
      const res = await listTenantPackage(this.queryParams);
      this.tenantPackageList = res.rows;
      this.total = res.total;
      this.loading = false;
    },

    // 租户套餐状态修改
    async handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      const [cancel,confirm] = await to(this.$modal.confirm("确认要\"" + text + "\"\"" + row.packageName + "\"套餐吗？"));
      if (cancel) {
        row.status = row.status === "0" ? "1" : "0";
      } else {
        await changePackageStatus(row.packageId, row.status);
        this.$modal.msgSuccess(text + "成功");
      }
    },

    // 取消按钮
    cancel() {
      this.reset();
      this.dialog.visible = false;
    },

    // 表单重置
    reset() {
      this.$refs.menuTreeRef && this.$refs.menuTreeRef.setCheckedKeys([]);
      this.menuExpand = false;
      this.menuNodeAll = false;
      this.form = { ...initFormData },
      this.$refs.tenantPackageFormRef && this.$refs.tenantPackageFormRef.resetFields();
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.$refs.queryFormRef.resetFields();
      this.handleQuery();
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.packageId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == "menu") {
        let treeList = this.menuOptions;
        for (let i = 0; i < treeList.length; i++) {
          if (this.$refs.menuTreeRef) {
            this.$refs.menuTreeRef.store.nodesMap[treeList[i].id].expanded = value;
          }
        }
      }
    },

    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == "menu") {
        this.$refs.menuTreeRef.setCheckedNodes(value ? this.menuOptions : []);
      }
    },

    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == "menu") {
        this.form.menuCheckStrictly = value;
      }
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getMenuTreeselect();
      this.dialog.visible = true;
      this.dialog.title = "添加租户套餐";
    },

    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.reset();
      let _packageId = row?.packageId || this.ids[0];
      let response = await getTenantPackage(_packageId);
      this.form = response.data;
      let res = await this.getPackageMenuTreeselect(_packageId);
      console.log("handleUpdate=====>",res)
      this.dialog.visible = true;
      this.dialog.title = "修改租户套餐";
      res.data.checkedKeys.forEach((v)=>{
        this.$nextTick(()=>{
          this.$refs.menuTreeRef.setChecked(v, true, false);
        });
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs.tenantPackageFormRef.validate(async (valid) => {
        if (valid) {
          this.buttonLoading = true;
          this.form.menuIds = this.getMenuAllCheckedKeys();
          if (this.form.packageId != null) {
            await updateTenantPackage(this.form).finally(() => this.buttonLoading = false);
          } else {
            await addTenantPackage(this.form).finally(()=> this.buttonLoading = false);
          }
          this.$modal.msgSuccess("操作成功");
          this.dialog.visible = false;
          await this.getList();
        }
      });
    },

    /** 删除按钮操作 */
    async handleDelete(row) {
      _packageIds = row?.packageId || this.ids;
      await this.$modal.confirm("是否确认删除租户套餐编号为\"" + _packageIds + "\"的数据项？").finally(()=>{
        this.loading = false;
      });
      await delTenantPackage(_packageIds);
      this.loading = true;
      await this.getList();
      this.$modal.msgSuccess("删除成功");
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download("system/tenantPackage/export", {
        ...queryParams.value
      }, `tenantPackage_${new Date().getTime()}.xlsx`);
    },
    // 流量配置
    handleSettings(row){
      this.curPackage = {...row}
      this.showLimiterSetting = true;
    },
  },
}
</script>